<template>
  <view class="content">
    <view class="con_body">
      <view class="head">
        <map
          show-compass
          :latitude="positionInfo.latitude"
          :longitude="positionInfo.longitude"
          :markers="markers"
        >
        </map>
      </view>
      <view class="body" v-if="rideInfo.is_unlock">
        <view class="body_info" v-if="rideInfo.is_start && !rideInfo.is_end">
          <view class="info">
            <label class="label_1">当前时速 : </label>
            <text class="text_1">{{ positionInfo.speed }}</text>
          </view>
          <view class="info_2">
            <label class="label_2">当前行驶时间 : </label>
            <text class="text_2">{{ hours }}:{{ minute }}:{{ second }}</text>
          </view>
        </view>
        <view class="body_info_2" v-else-if="rideInfo.is_end">
          <view class="info">
            <label class="label_1">出发时间 : </label>
            <text class="text_1">{{ rideInfo.startTime | dateFormat }}</text>
          </view>
          <view class="info_2">
            <label class="label_2">骑行时长 : </label>
            <text class="text_2">{{ hours }}:{{ minute }}:{{ second }}</text>
          </view>
        </view>
        <view
          class="body_ride"
          v-if="!rideInfo.is_end"
          :class="{ body_ride_star: !rideInfo.is_start }"
        >
          <button
            @click="stopInterval"
            :disabled="!rideInfo.is_start"
            :class="{ start_btn: !rideInfo.is_start }"
          >
            骑行结束
          </button>
          <button
            @click="startInterval"
            :disabled="rideInfo.is_start"
            :class="{ start_btn: rideInfo.is_start }"
          >
            开始骑行
          </button>
          <!-- <button @click="resetInterval">重新开始</button> -->
        </view>
        <view class="body_ride" v-else>
          <button class="endbtn" @click="comeBack">结束本次骑行</button>
        </view>
      </view>
      <view v-else class="bottom">
        <view class="bot_body">
          <button @click="unlock">蓝牙连接开锁</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 引入请求模块
import { postRequest } from "@/api/api.js";
// 引入url
import { postRideHistory } from "@/api/request.js";
export default {
  name: "ride",
  created() {
    // 获取当前位置信息
    // this.getPos();
    this.getRideInfo();
    this.authorization();
  },
  data() {
    return {
      positionInfo: {},
      rideInfo: {
        startTime: "",
        endTime: "",
        timerNum: 0,
        is_start: false,
        is_unlock: false,
        is_end: false,
        is_return: false,
        watch: false,
        start_latitude: 0,
        start_longitude: 0,
        end_latitude: 0,
        end_longitude: 0,
        duration: "",
      },
      is_success: false,
      is_located: true,
      satrtTime: "",
      endTime: "",
      markers: [
        {
          id: 0,
          latitude: 24.10014,
          longitude: 115.25984,
          iconPath: "/static/icon/pos.png",
          width: 30,
          height: 30,
        },
      ],
      timerNum: 0,
      hours: "0" + 0, // 时
      minute: "0" + 0, // 分
      second: "0" + 0, // 秒
    };
  },
  methods: {
    // 获取地图信息
    async getPos() {
      const that = this;
      await uni.getLocation({
        type: "wgs84",
        geocode: true,
        success: async function (res) {
          that.positionInfo = res;
          that.markers[0].longitude = res.longitude;
          that.markers[0].latitude = res.latitude;
          console.log("当前位置的经度：" + res.longitude);
          console.log("当前位置的纬度：" + res.latitude);
        },
        fail: (err) => {
          console.log(err);
        },
      });
    },
    // 提示用户获取位置信息 监听位置变化
    async authorization() {
      let that = this;
      try {
        wx.authorize({
          scope: "scope.userLocation",
          success: async (res) => {
            console.log(res);
            wx.getSetting({
              success: async (res) => {
                console.log(res);
                if (!res.authSetting["scope.userLocation"]) {
                  //打开提示框，提示前往设置页面
                  that.toSetting();
                  console.log("未开启定位");
                } else {
                  await that.getWxLocation(false);
                  // wx.getSystemInfo({
                  //   success: async (res) => {
                  //     if (res.locationEnabled) {
                  //       (that.is_located = true),
                  //         await that.getWxLocation(false);
                  //     } else {
                  //       uni.showToast({
                  //         icon: "none",
                  //         title: "检测到当前未开启定位，请先开启定位",
                  //         duration: 2500,
                  //       });
                  //     }
                  //   },
                  // });
                }
              },
            });
          },
          // 授权失败
          fail(err) {
            err = err["errMsg"];
            uni
              .showModal({
                title: "温馨提示",
                content: "为享受智能小程序，您必须授权!",
                showCancel: false,
                confirmText: "确认授权",
              })
              // 这里只设置了确认按钮，没有取消按钮
              .then((res) => {
                //res ： [null, {cancel: false, confirm: true, errMsg: 'showModal: ok'}]
                if (res[1]["confirm"]) {
                  // 点击了确认按钮时
                  // 调用下边方法时，会弹出 【使用我的地理位置】界面， 未设置直接返回，还是会走fail授权失败的函数，
                  // 还是会弹出上边的温馨提示！！！
                  // 如果设置, scope.userLocation: true
                  uni.openSetting({
                    success(res) {
                      // 如果不设置，res结果：
                      // {errMsg: "openSetting:ok", authSetting: {scope.userLocation: false}}
                      // 如果设置, res结果：
                      // {errMsg: "openSetting:ok", authSetting: {scope.userLocation: true}}
                      // console.log('小程序设置界面：', res)
                    },
                  });
                }
              });
          },
        });
      } catch (error) {
        wx.authorize({
          scope: "scope.userLocation",
          success: async (res) => {
            await that.getWxLocation(false);
          },
        });
        return;
      }
    },
    // 获取定位信息
    getWxLocation(status, value) {
      const that = this;
      // if (!status && !that.is_start) {
      //   wx.showLoading({
      //     title: "定位中...",
      //     mask: true,
      //   });
      // }
      return new Promise((resolve, reject) => {
        let _locationChangeFn = async (res) => {
          console.log("location change", res);
          // if (!status && !that.is_start) {
          //   wx.hideLoading();
          // }
          if (value == "start") {
            that.rideInfo.start_latitude = res.latitude;
            that.rideInfo.start_longitude = res.longitude;
          } else if (value == "end") {
            that.rideInfo.end_latitude = res.latitude;
            that.rideInfo.end_longitude = res.longitude;
            console.log("--------here------------");
            await that.postRide();
          } else {
            that.positionInfo = res;
          }
          if (status || !this.rideInfo.is_start) {
            console.log("关闭位置监听");
            wx.offLocationChange(_locationChangeFn);
            wx.stopLocationUpdate({
              success: (res) => {
                console.log("停止位置监听");
                console.log(res);
              },
              fail: (err) => {
                console.log(err);
              },
            });
          }
        };
        wx.startLocationUpdate({
          success: (res) => {
            console.log("开启位置监听");
            console.log(res);
            wx.onLocationChange(_locationChangeFn);
            resolve(res);
          },
          fail: (err) => {
            console.log("获取当前位置失败", err);
            // wx.hideLoading();
            reject(err);
          },
        });
      });
    },
    // 引导用户设置位置信息
    toSetting() {
      let that = this;
      wx.openSetting({
        success(res) {
          console.log(res);
          if (res.authSetting["scope.userLocation"]) {
            // res.authSetting["scope.userLocation"]为trueb表示用户已同意获得定位信息，此时调用getlocation可以拿到信息
            that.authorization();
          }
        },
      });
    },
    // 监听位置变化
    watchpos() {},
    // 获取骑行信息，主要用于用户返回继续记录信息
    getRideInfo() {
      let info = uni.getStorageSync("rideInfo");
      console.log("----------------getrideInfo----------------------");
      console.log(info);
      if (info) {
        this.rideInfo = info;
        this.rideInfo.is_return = true;
        console.log("----------------thisrideInfo----------------------");
        console.log(this.rideInfo);
        // 计算时间差，继续计时
        this.getTimeDif();
      }
    },
    // 获取两个时间的时间差
    getTimeDif() {
      let date1 = this.rideInfo.startTime; //开始时间
      date1 = new Date(date1);
      let date2 = new Date(); //结束时间
      let date3 = date2.getTime() - date1.getTime(); //时间差的毫秒数
      //计算出相差天数
      let days = Math.floor(date3 / (24 * 3600 * 1000));
      //计算出小时数
      let leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
      let hours = Math.floor(leave1 / (3600 * 1000));
      //计算相差分钟数
      let leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
      let minutes = Math.floor(leave2 / (60 * 1000));
      //计算相差秒数
      let leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
      let seconds = Math.round(leave3 / 1000);
      if (hours < 10) {
        this.hours = "0" + hours;
      } else {
        this.hours = hours;
      }
      if (minutes < 10) {
        this.minute = "0" + minutes;
      } else {
        this.minute = minutes;
      }
      if (seconds < 10) {
        this.second = "0" + seconds;
      } else {
        this.second = seconds;
      }
      // 启动计时器
      this.startInterval();
      console.log(
        " 相差 " +
          days +
          "天 " +
          hours +
          "小时 " +
          minutes +
          " 分钟" +
          seconds +
          " 秒"
      );
    },
    // 计时器
    startInterval() {
      if (!this.rideInfo.is_start || this.rideInfo.is_return) {
        if (!this.rideInfo.is_return) {
          // this.rideInfo.startTime = Vue.filter("dateFormat", new Date());
          this.rideInfo.startTime = this.$options.filters["dateFormat"](
            new Date()
          );
          console.log(this.rideInfo.startTime);
          // this.watchpos("on", "start");
          this.getWxLocation(false, "start");
        }
        const that = this;
        that.rideInfo.is_start = true;
        var second = that.second;
        var minute = that.minute;
        var hours = that.hours;
        that.timerNum = setInterval(function () {
          // 设置定时器
          second++;
          if (second >= 60) {
            second = 0; //  大于等于60秒归零
            minute++;
            if (minute >= 60) {
              minute = 0; //  大于等于60分归零
              hours++;
              if (hours < 10) {
                // 少于10补零
                that.hours = "0" + hours;
              } else {
                that.hours = hours;
              }
            }
            if (minute < 10) {
              // 少于10补零
              that.minute = "0" + minute;
            } else {
              that.minute = minute;
            }
          }
          if (second < 10) {
            // 少于10补零
            that.second = "0" + second;
          } else {
            that.second = second;
          }
        }, 1000);
        that.rideInfo.timerNum = that.timerNum;
        // console.log(that.rideInfo);
        uni.setStorage({
          key: "rideInfo",
          data: that.rideInfo,
          success: function () {
            console.log("set rideInfo success");
          },
          fail: (err) => {
            console.log(err);
          },
        });
      }
    },
    // 停止计时
    async stopInterval() {
      await this.getWxLocation(true, "end");
    },
    async postRide() {
      this.rideInfo.endTime = this.$options.filters["dateFormat"](new Date());
      console.log(this.rideInfo.endTime);
      this.rideInfo.duration =
        this.hours + ":" + this.minute + ":" + this.second;
      const result = await postRequest(postRideHistory, this.rideInfo);
      console.log(result);
      if (result[1].data.status === 0) {
        clearInterval(this.timerNum);
        this.rideInfo.is_end = true;
        console.log("----------stopInterval rideInfo------------");
        console.log(this.rideInfo);
        // 关闭位置监听
        this.watchpos("off");
        uni.removeStorageSync("rideInfo");
      } else {
        this.getWxLocation(false);
        uni.showToast({
          icon: "none",
          title: "网络请求失败！请稍后再试",
          duration: 2500,
        });
      }
    },
    // 解锁
    unlock() {
      if (this.is_located) {
        this.rideInfo.is_unlock = true;
      }
      this.authorization();
    },
    // 结束骑行
    comeBack() {
      // uni.redirectTo({
      //   url: "/pages/index/index",
      // });
      uni.switchTab({
        url: "/pages/index/index",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
view {
  transition: all 2s ease 0s;
  -webkit-transition: all 2s ease 0s; /* Safari */
}
.content {
  position: relative;
  height: 100vh;
  background-color: aliceblue;
  .con_body {
    transition: all 1s ease 0s;
    .head {
      map {
        width: 100%;
        height: 70vh;
      }
    }
    .body {
      height: 30vh;
      .body_info {
        height: 60%;
        display: flex;
        flex-wrap: wrap;
        text-align: center;
        .info {
          width: 100%;
          height: 60%;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .info_2 {
          width: 100%;
          height: 40%;
          display: flex;
          justify-content: center;
          align-items: flex-start;
        }
        label {
          width: 50%;
          text-align: right;
          // padding-right: 10rpx;
          font-size: 30rxp;
          font-weight: bold;
          color: #595959;
        }
        text {
          width: 50%;
          text-align: left;
          padding-left: 30rpx;
          font-weight: bold;
          font-size: 30rxp;
          color: #595959;
        }
      }
      .body_info_2 {
        height: 60%;
        display: flex;
        flex-wrap: wrap;
        text-align: center;
        .info {
          width: 100%;
          height: 60%;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .info_2 {
          width: 100%;
          height: 40%;
          display: flex;
          justify-content: center;
          align-items: flex-start;
        }
        label {
          width: 35%;
          text-align: right;
          // padding-right: 10rpx;
          font-size: 30rxp;
          font-weight: bold;
          color: #595959;
        }
        text {
          width: 65%;
          // text-align: left;
          // padding-right: 30rpx;
          font-weight: bold;
          font-size: 30rxp;
          color: #595959;
        }
      }
      .body_ride {
        height: 40%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        transition: all 1s ease 0s;
        button {
          width: 300rpx;
          background: rgb(247, 236, 82);
          color: #fff;
          border: 0;
        }
        .endbtn {
          width: 60%;
          background: rgb(95, 95, 94);
          color: #fff;
        }
        // button:active {
        //   width: 300rpx;
        //   background: rgb(150, 144, 61);
        //   color: #fff;
        // }
        .start_btn {
          width: 300rpx;
          background: rgb(150, 144, 61);
          color: #fff;
        }
      }
      .body_ride_star {
        height: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        transition: all 1s ease 0s;
        button {
          width: 300rpx;
          background: rgb(247, 236, 82);
          color: #fff;
        }
      }
    }
    .bottom {
      height: 30vh;
      transition: height 2s ease 2s;
      .bot_body {
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;

        button {
          width: 60%;
          background: rgb(95, 95, 94);
          color: #fff;
        }
      }
    }
  }
}

// .ride_status-enter-active {
//   transition: opacity 0.5s;
// }
// .ride_status-enter {
//   opacity: 0;
// }
// .ride_status-leave-active {
//   transition: opacity 0.5s;
// }
// .ride_status-leave-to {
//   opacity: 0;
// }
</style>